package com.example.administrator.androidros.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.activity.MyInfoActivity;
import com.example.administrator.androidros.activity.PermissionManageActivity;
import com.example.administrator.androidros.base.BaseFragment;
import com.example.administrator.androidros.model.MemberModel;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.AgentUtils;
import com.example.administrator.androidros.utils.DisplayHelper;
import com.example.administrator.androidros.utils.FileUtil;
import com.example.administrator.androidros.utils.ServerConstants;
import com.example.administrator.androidros.utils.UUIDUtil;
import com.example.administrator.androidros.widget.CustomActionSheetDialog;
import com.example.administrator.androidros.widget.CustomDialog;
import com.example.administrator.androidros.widget.CustomTipDialog;

import java.io.File;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/1/16.
 */

public class MyFragment extends BaseFragment {
    @BindView(R.id.fragment_my_ll_member_information)
    protected LinearLayout fragment_my_ll_member_information;
    @BindView(R.id.fragment_my_img_avatar)
    protected ImageView fragment_my_img_avatar;
    @BindView(R.id.fragment_my_tv_name)
    protected TextView fragment_my_tv_name;
    @BindView(R.id.fragment_my_tv_telephone)
    protected TextView fragment_my_tv_telephone;

    private static final int REQUEST_CODE_PICK_IMAGE = 10101;
    private static final int REQUEST_CODE_CAPTURE_CAMERA = 10102;
    private static final int REQUEST_CODE_CROP = 10103;
    private static final int REQUEST_CODE_CROP_SYSTEM = 10104;

    private CustomActionSheetDialog customActionSheetDialog;
    private String tempPath = null;
    private String photoPath = null;
    private Uri uri = null;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    protected void initData(View view, Bundle savedInstanceState) {
        setStatusBar();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void onFailure(int requestCode, Object object) {
        showToast(R.string.common_response_failure);
        stopTipDialog();
    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
                case 1001:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        String newUrl = (String) HttpUtils.getData(object, String.class);
                        //更新到memberPic
                        updateAvatar(newUrl);
                    }
                    break;
                case 1002:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        MemberModel memberModel = (MemberModel) HttpUtils.getData(object, MemberModel.class);
                        AgentSharedPreferences.saveMemberInfo(mBaseActivity, memberModel);
                        initMemberInfo();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                case 1003:
                    Log.d("hhc", "onSuccess: "+object);
                    break;
                default:
                    break;
            }
        }
    }

    @OnClick(R.id.fragment_my_img_avatar)
    protected void onAvatarClick() {
        requestSdCardPermission();
    }

    protected void setStatusBar() {
        //设置状态栏颜色和位移一段距离
        DisplayHelper.setStatusBarColor(mBaseActivity, R.color.common_head);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) fragment_my_ll_member_information.getLayoutParams();
        lp.setMargins(0, DisplayHelper.getStatusBarHeight(mBaseActivity), 0, 0);
    }

    protected void initMemberInfo() {
        MemberModel memberModel = AgentSharedPreferences.getMemberInfo(mBaseActivity);
        if (memberModel.getMemberName() != null && !memberModel.getMemberName().equals("")) {
            fragment_my_tv_name.setText(memberModel.getMemberName());
        } else {
            fragment_my_tv_name.setText("未设置");
        }
        fragment_my_tv_telephone.setText(memberModel.getMemberTelephone());

        if (memberModel.getMemberPic() != null && !memberModel.getMemberPic().equals("")) {
            Glide.with(mBaseActivity).load(ServerConstants.FILE_SERVER_URL + memberModel.getMemberPic()).crossFade().into(fragment_my_img_avatar);
        }
    }

    /**
     * 个人信息
     */
    @OnClick({R.id.fragment_my_ll_member_info, R.id.fragment_my_img_go})
    protected void onInfoClick() {
        startOtherActivity(MyInfoActivity.class, null);
    }

    /**
     * 我的信息
     */
    @OnClick(R.id.fragment_my_ll_message)
    protected void onMessageClick() {

    }

    /**
     * 网关设置
     */
    @OnClick(R.id.fragment_my_ll_gateway_setup)
    protected void onGatewaySetupClick() {

    }

    @OnClick(R.id.fragment_my_ll_permission_manage)
    protected void onPermissionManage() {
        startOtherActivity(PermissionManageActivity.class, null);
    }

    /**
     * 版本更新
     */
    @OnClick(R.id.fragment_my_ll_version_update)
    protected void onVersionUpdateClick() {
        new CustomDialog.Builder(mBaseActivity)
                .setTitle("智能家居")
//                .setMessage("有新的版本，现在更新?")
                .setMessage("当前版本已经是最新版。")
                .setButton(DialogInterface.BUTTON_POSITIVE, "确定", null)
                .setButton(DialogInterface.BUTTON_NEGATIVE, "取消", null)
                .setCancelable(false)
                .create()
                .show();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", "13160675089");
        jsonObject.put("applianceId", "123455");
        HttpUtils.post(mBaseActivity, 1003, ServerConstants.QUERY_AUTHORIZED_LIST, jsonObject.toString(), this);

    }

    /**
     * 关于与帮助
     */
    @OnClick(R.id.fragment_my_ll_about_and_help)
    protected void onAboutAndHelpClick() {
        new CustomDialog.Builder(mBaseActivity)
                .setTitle("智能家居")
                .setMessage("帮助与反馈:1066492750@qq.com")
                .setButton(DialogInterface.BUTTON_POSITIVE, "确认", null)
                .setCancelable(false)
                .create()
                .show();
    }

    /**
     * 退出登录
     */
    @OnClick(R.id.fragment_my_bt_logout)
    protected void onLogoutClick() {
        showInformationDialog("确定要退出登录吗?", DialogInterface.BUTTON_POSITIVE, DialogInterface.BUTTON_NEGATIVE, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    exit();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initMemberInfo();
    }

    private void requestCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteSdPermission = getActivity().checkSelfPermission(Manifest.permission.CAMERA);
            if (hasWriteSdPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.CAMERA
                }, 2002);
            } else {
                //启动相机拍照
                startCamera();
            }
        } else {
            //启动相机拍照
            startCamera();
        }
    }

    private void startCamera() {
        // 拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {

            // 在SD卡创建一个新的文件
            File currentFile = AgentUtils.createImageUri();
            // 真实文件路径
            tempPath = currentFile.getAbsolutePath().toString();
            // 在SD卡创建一个新的文件
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                uri = FileProvider.getUriForFile(mBaseActivity, "com.example.administrator.androidros.fileprovider", currentFile);
            } else {
                uri = Uri.fromFile(currentFile);
            }
            Log.d("hhc", "startCamera: " + uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置输出路径到新建的文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        // 拍照回调
        startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMERA);
    }

    private void selectFromSdCard() {
//        // 从相册选择
//        Intent intentTemp = new Intent();
//        intentTemp.setClass(getActivity(), ImagePickGridActivity.class);
//        intentTemp.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
//        intentTemp.putExtra("ok_title", "确定");
//        intentTemp.putExtra(ImagePickerConsts.REQUEST_KEY_MAX_COUNT, 1);
//        startActivityForResult(intentTemp, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 请求写入sd卡
        if (requestCode == 2000) {
            if (permissions[0].equals(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意
                selectAvatarPopup();
            } else {
                // 用户不同意
                showToast(getString(R.string.common_user_refuse_authorize));
            }
        } else if (requestCode == 2002) {
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意
                startCamera();
            } else {
                showToast("手机权限不足，无法拍摄头像");
            }
        }
    }

    private void requestSdCardPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteSdPermission = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWriteSdPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, 2000);
            } else {
                selectAvatarPopup();
            }
        } else {
            selectAvatarPopup();
        }
    }

    private void selectAvatarPopup() {
        customActionSheetDialog = new CustomActionSheetDialog.Builder(mBaseActivity)
                .addMenu("拍照", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        customActionSheetDialog.dismiss();
                        requestCameraPermission();
                    }
                }).
//                        addMenu("从手机相册选择", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        customActionSheetDialog.dismiss();
//                        selectFromSdCard();
//                    }
//                }).
        create();
        customActionSheetDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = null;
        if (data != null) {
            bundle = data.getExtras();
        }
        switch (requestCode) {
            case REQUEST_CODE_CAPTURE_CAMERA:
                if (Activity.RESULT_OK == resultCode) {
                    //直接上传
                    File file = new File(tempPath);
                    Glide.with(mBaseActivity).load(uri).into((fragment_my_img_avatar));
                    uploadAvatar(file);
//                    //不裁剪
//                    photoPath = AgentUtils.getImageCachePath() + "/" + UUID.randomUUID().toString() + ".jpg";
////                    String imageFilePath = AgentUtils.getImageCachePath() + "/temp.jpg";// 设置图片的保存路径
////                    Log.d("hhc", "onActivityResult: imageFilePath=" + imageFilePath);
//                    File currentFile = new File(photoPath);
//                    Log.d("hhc", "onActivityResult: imageFilePath=" + photoPath);
//
//                    Uri mUri;
//                    Intent cropIntent = new Intent("com.android.camera.action.CROP");
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//                        mUri = FileProvider.getUriForFile(mBaseActivity, "com.example.administrator.androidros.fileprovider", currentFile);
//                    } else {
//                        mUri = Uri.fromFile(currentFile);
//                    }
//                    Log.d("hhc", "onActivityResult: mUri=" + mUri);
////                    mBaseActivity.grantUriPermission(mBaseActivity.getPackageName(), mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//                    cropIntent.setDataAndType(uri, "image/*");
//                    cropIntent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
//                    cropIntent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
//                    cropIntent.putExtra("aspectY", 1);// x:y=1:1
//                    cropIntent.putExtra("outputX", 360);//图片输出大小
//                    cropIntent.putExtra("outputY", 360);
//                    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
////                    cropIntent.putExtra("return-data", true);
//                    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//                    cropIntent.putExtra("noFaceDetection", false); // no face detection
//                    startActivityForResult(cropIntent, REQUEST_CODE_CROP_SYSTEM);
                }
                break;
            case REQUEST_CODE_CROP_SYSTEM:
                Log.d("hhc", "onActivityResult: 裁剪回调" + bundle);
                // use bundle to get data
                if (bundle != null) {
//                    photoPath = bundle.getString("backValue");
//                    Log.d("hhc", "onActivityResult: " + photoPath);
                    File photo = new File(photoPath);
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = FileProvider.getUriForFile(mBaseActivity, "com.example.administrator.androidros.fileprovider", photo);
                    } else {
                        uri = Uri.fromFile(photo);
                    }
                    Log.d("hhc", "onActivityResult: uri=" + uri);
                    Glide.with(mBaseActivity).load(uri).into((fragment_my_img_avatar));
                    uploadAvatar(photo);
                } else {
//				showToast("");
                }
                break;
            default:
                break;
        }
    }

    //上传头像，获取地址
    private void uploadAvatar(File file) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileName", UUIDUtil.get36UUID());
        jsonObject.put("file", FileUtil.encodeBase64File(file));
        jsonObject.put("suffix", "jpg");
        HttpUtils.post(mBaseActivity, 1001, ServerConstants.UPLOAD_AVATAR, jsonObject.toString(), this);
    }

    //更新用户头像地址
    private void updateAvatar(String url) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberTelephone", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("memberPic", url);
        HttpUtils.post(mBaseActivity, 1002, ServerConstants.UPDATE_MEMBER_INFO, jsonObject.toString(), this);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_updating), true);
    }
}
